package com.kylin.pojo;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PC {

    public static void main(String[] args) {
        Data data = new Data();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                data.product();
            }, "AA").start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                data.consumer();
            }, "BB").start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                data.product();
            }, "CC").start();
        }
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                data.consumer();
            }, "DD").start();
        }
    }
}

class Data {

    private int size = 0;
    private Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void product() {
        lock.lock();
        try {
            while (size >= 10) {
                condition.await();
            }
            for (int i = 0; i < 10; i++) {
                size++;
                System.out.println(Thread.currentThread().getName() + "生产了" + size);
            }
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void consumer() {
        lock.lock();
        try {
            while (size <= 0) {
                condition.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + "消费了" + size);
                size--;
            }
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


